<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
use Illuminate\Support\Facades\Hash;
use Mews\Captcha\Facades\Captcha;
use App\Models\User;


class AuthLoginRequest extends FormRequest
{

    public function rules(): array
    {
        return [
            'username' => 'required|string|max:255',
            'password' => 'required|string|min:6',
            'captchaCode' => 'required|string',
            'captchaKey' => 'required|string',
        ];
    }

    public function after(): array
    {
        return [
            function (Validator $validator) {
                $isValid = Captcha::check($this->captchaCode, $this->captchaKey);

                if (!$isValid) {
                    $validator->errors()->add(
                        'captchaCode',
                        '验证码错误'
                    );
                }
            },
            function (Validator $validator) {
                $userExists = User::where('username', $this->username)->exists();

                if (!$userExists) {
                    $validator->errors()->add(
                        'username',
                        '用户不存在'
                    );
                }
            },
            function (Validator $validator) {
                $user = User::where('username', $this->username)->first();

                if ($user && !Hash::check($this->password, $user->password)) {
                    $validator->errors()->add(
                        'password',
                        '账号或密码错误'
                    );
                }
            }
        ];
    }
}
